<template>
  <div class="app-container">
    <!-- <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px" class="white-normal-box">
     <el-form-item label="订单名称" prop="orderName">
        <el-input
          v-model="queryParams.orderName"
          placeholder="请输入订单名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单数量" prop="orderNumber">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入订单数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单价格" prop="orderPrice">
        <el-input
          v-model="queryParams.orderPrice"
          placeholder="请输入订单价格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单状态" prop="orderState">
        <el-input
          v-model="queryParams.orderState"
          placeholder="请输入订单状态"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单时间" prop="orderTime">
        <el-date-picker clearable
          v-model="queryParams.orderTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择订单时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
       <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form> -->

    <div class="white-normal-box">
      <el-row :gutter="10" class="mb20">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:order:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:order:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:order:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:order:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
  <!--     <el-table-column label="主键id" align="center" prop="id" /> -->
        <el-table-column label="订单名称" align="center" prop="orderName" />
        <el-table-column label="订单数量" align="center" prop="orderNumber" />
        <el-table-column label="订单价格" align="center" prop="orderPrice" />
        <el-table-column label="订单状态" align="center" prop="orderState" >
          <template slot-scope="scope">
                                  <span v-if="scope.row.orderState == 0">待支付</span>
                                  <span v-if="scope.row.orderState == 1">已支付</span>
                              </template>
        </el-table-column>
      <!--  <el-table-column label="下单人" align="center" prop="userId" /> -->
  <!--       <el-table-column label="利润" align="center" prop="profit" />
  -->        <el-table-column label="下单人" align="center" prop="nickName" />
  <!--        <el-table-column label="交易凭证" align="center" prop="proof" />
  -->        <el-table-column
                    label="交易凭证"
                    prop="proof"
                    align="center"
                    width="100px"
                  >
                    <template slot-scope="scope">
                              <el-image
                                @click="bigImg(`${scope.row.proof}`)"
                                style="width: 50px; height: 50px; margin-bottom:-4px"
                                :src="`${scope.row.proof}`"
                                :preview-src-list="srcList"
                              >
                              </el-image>
                            </template>
                          </el-table-column>


              <el-table-column label="交易流水号" align="center" prop="proofCode" />
          <el-table-column show-overflow-tooltip width="200" label="账号" align="center" prop="account" />
        <el-table-column label="订单时间" align="center" prop="orderTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.orderTime, ' {y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button v-if="scope.row.orderState == 0"
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row,true)"
              v-hasPermi="['system:order:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row,false)"
              v-hasPermi="['system:order:hetong']"
            >查看合同</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:order:remove']"
            >删除</el-button>

          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    

    <!-- 添加或修改订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

     <!--  <el-form-item label="订单名称" prop="orderName">
          <el-input v-model="form.orderName" placeholder="请输入订单名称" />
        </el-form-item>
        <el-form-item label="订单数量" prop="orderNumber">
          <el-input v-model="form.orderNumber" placeholder="请输入订单数量" />
        </el-form-item>
        <el-form-item label="订单价格" prop="orderPrice">
          <el-input v-model="form.orderPrice" placeholder="请输入订单价格" />
        </el-form-item> -->
        <el-form-item v-if="openss" label="订单状态" prop="orderState">
<!--          <el-input v-model="form.orderState" placeholder="请输入订单状态" />
 -->           <el-radio-group v-model="form.orderState">
                            <el-radio label="0">待支付</el-radio>
                            <el-radio label="1">已支付</el-radio>
                          </el-radio-group>
        </el-form-item>
        <el-form-item label="交易流水号" prop="proofCode">
          <el-input v-model="form.proofCode" placeholder="请输入交易流水号" />
        </el-form-item>




        <el-form-item v-if="!openss"
          label="合同">


          <el-upload
            :action="uploadFileUrl"
            :headers="headers"
            :file-list="form.contractCopy"
            list-type="picture-card"
            :limit="3"
            :on-exceed="handleExceed"
            :before-upload="beforeAvatarUpload"
            :on-preview="handlePictureCardPreview"
            :on-success="handleAvatarSuccess"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>



<!--          <el-upload-->
<!--            list-type="picture-card"-->
<!--            :file-list="fileList"-->
<!--            :multiple="true"-->
<!--            :limit="3"-->
<!--            :show-file-list="false"-->
<!--            accept=".png,.jpg"-->
<!--            class="avatar-uploader"-->
<!--            :action="uploadFileUrl"-->
<!--            :headers="headers"-->
<!--            :on-success="handleAvatarSuccess"-->
<!--            :on-error="handleUploadError"-->
<!--            :before-upload="beforeAvatarUpload">-->
<!--            <div v-if="form.contract" v-for="(item,index) in form.contract" :key="index">-->
<!--              <img  :src="item" class="avatar" style="width: 100px;height: 100px">-->
<!--            </div>-->
<!--            <i v-else class="el-icon-plus avatar-uploader-icon"></i>-->
<!--          </el-upload>-->










        </el-form-item>
<!--        <el-form-item label="交易凭证" prop="proof">-->
<!--          <el-input v-model="form.proof" placeholder="请输入交易凭证" />-->
<!--        </el-form-item>-->
        <!-- <el-form-item label="订单时间" prop="orderTime">
          <el-date-picker clearable
            v-model="form.orderTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择订单时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="利润" prop="profit">
          <el-input v-model="form.profit" placeholder="请输入利润" />
        </el-form-item>
        <el-form-item label="交易凭证" prop="proof">
          <el-input v-model="form.proof" placeholder="请输入交易凭证" />
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model="form.account" placeholder="请输入账号" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { getToken } from "@/utils/auth";
import { listOrder, getOrder, delOrder, addOrder, updateOrder,updateContract } from "@/api/system/order";

export default {
  name: "Order",
  data() {
    return {
      openss:false,
      fileList: [{name:'food.jpeg',url:'http://43.138.186.106:8080/profile/upload/2023/11/30/home3_20231130145543A047.png'},{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}, {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}],
      dialogImageUrl: '',
      dialogVisible: false,
      // 大小限制(MB)
      maxSize: 10 * 1024 * 1024,  //限制的文件大小，单位是字节
      // 文件类型, 例如['png', 'jpg', 'jpeg']
      acceptType: ['jpg', 'jpeg', 'png'],  //限制的文件类型
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传文件服务器地址
      limit:3,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderName: null,
        orderNumber: null,
        orderPrice: null,
        orderState: null,
        orderTime: null
      },
      // 表单参数
      form: {
        contractCopy:[],
        contract:null
      },
      // 表单校验
      rules: {
      },
        srcList:["https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg"]


    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 查看合同
    watchContract(){

    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    handleRemove(file) {
      var url=null;
      if (file.response!=null){
        url = file.response;
      }else{
        url = file;
      }
      for (let i = 0; i < this.form.contractCopy.length; i++) {
        if(this.form.contractCopy[i].url === url.url)
        {
          this.form.contractCopy.splice(i,1);
          break;
        }
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 上传成功回调
    handleAvatarSuccess(res) {
      var list = [];

      this.form.contractCopy.forEach(item => {
        if(item.name == 'a.png')
        {
          const obj = {
            name:'a.png',
            url:item.url
          };
          list.push(obj)
        }
        });
      const obj1 = {
        name:'a.png',
        status:"success",
        url:res.url
      };
      list.push(obj1)
      this.form.contractCopy=list;
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading();
    },
    // 上传前校检格式和大小
    beforeAvatarUpload(file) {
      const isJPG = this.acceptType.indexOf(file.type.split('/')[1]) !== -1;
      if (!isJPG) {
        this.$message.error('只能上传' + this.acceptType.join(',') + '格式的文件!');
        return false
      }
      const isLtSize = file.size / 1024 / 1024 < this.maxSize / 1024 / 1024;
      if (!isLtSize) {
        this.$message.error('上传文件大小不能超过' + this.maxSize / 1024 / 1024 + 'MB!');
        return false
      }
    },
    /** 查询订单列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderName: null,
        orderNumber: null,
        orderPrice: null,
        orderState: null,
        orderTime: null,
        contract:null,
        contractCopy:[]
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row,msg) {
      this.openss = msg;
      this.reset();
      const id = row.id || this.ids;
      getOrder(id).then(response => {

        var list = [];
        if (response.data.contract !== null && response.data.contract !==''){
          response.data.contract.split(",").forEach(item => {
            const obj = {
              name:'a.png',
              url:item
            };
            list.push(obj)
          });
        }
        this.form = response.data;
          this.form.contractCopy = list;
        // this.form.contract = this.form.contract.split(",")
        this.open = true;
        this.title = "修改订单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            var list = this.form.contractCopy;
            var msg = "";
            for (let i = 0; i < list.length; i++) {
              if(list[i].name === 'a.png')
              {
                if (msg === '')
                {
                  msg = list[i].url
                }else{
                  msg = msg + "," + list[i].url
                }
              }
            }
            this.form.contract = msg;
            if (!this.openss)
            {
              this.form.orderState = null;
              updateContract(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            }else{
              this.form.contract = null;
              updateOrder(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            }

          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },


    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除订单编号为"' + ids + '"的数据项？').then(function() {
        return delOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    },
      bigImg(url) {
          this.srcList[0] = url;
          Error("测试"+url)
        }
  }
};

</script>
<style>
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
